package com.codeoss.framework.view.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.Button;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.IDataBinding;
import com.codeoss.framework.view.component.IDataType;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.store.IComponentStore;

@Service
public class ButtonComponentService extends ComponentService {
	@Autowired
	private IScriptServiceStore scriptServiceStore;
	@Autowired
	private IComponentStore componentStore;
	@Autowired
	private IConverterStore converterStore;
	@Override
	public void processEvent(YunContext yunContext, Component component, String eventType) {
		// TODO Auto-generated method stub
		Button button=(Button)component;
		Expression readOnlyExpression=button.getReadOnlyExpression();
		if(readOnlyExpression!=null) {
			boolean b=(boolean)scriptServiceStore.getScriptService(readOnlyExpression).eval(readOnlyExpression.getScript(), yunContext.getVarValueMap());
			if(b) {
				throw new RuntimeException("没有权限");
			}
		}
		if ("clickEvent".equals(eventType)) {
			String serverPageCode=button.getServerPageCode();
			if(!StringUtils.isEmpty(serverPageCode)) {
				Map<String,String> dataMap=yunContext.getViewRequest().getData();
				Page buttonPage=componentStore.get(serverPageCode);
				List<IDataBinding> formDataBindingList=buttonPage.getAttribute("key_form_field_list");
				Map<String,Object> paraMap=new HashMap<String,Object>();
				for(int i=0;i<formDataBindingList.size();i++) {
					String sValue=dataMap.get(button.getId()+"_"+formDataBindingList.get(i).getDataField());
					IDataType dataType=(IDataType)formDataBindingList.get(i);
					IConverter converter=converterStore.getConverter(dataType.getDataType());
					if(!StringUtils.isEmpty(sValue)) {
						Object value=converter.convertStringToObject(sValue);
						paraMap.put(formDataBindingList.get(i).getDataField(), value);
					}
				}
				Expression onClickExpression = component.getOnClickExpression();
				if (onClickExpression != null) {
					Map<String,Object> bindingMap=new HashMap<String,Object>();
					bindingMap.put("paraMap", paraMap);
					executeEventExpression(yunContext, component, onClickExpression,bindingMap);
				}
			}else {
				super.processEvent(yunContext, component, eventType);
			}
		}
	}
}
